package com.ruoyi.controller;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.domain.Administration;
import com.ruoyi.domain.AdsRecoverStation;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.service.IAdministrationService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.domain.Kind;
import com.ruoyi.util.FileUploadUtil;
import com.ruoyi.util.SftpProperties;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 审批管理Controller
 *
 * @author ya
 * @date 2025-01-18
 */
@RestController
@RequestMapping("/administration/administration")
public class AdministrationController extends BaseController
{
    @Autowired
    private IAdministrationService administrationService;

    @Autowired
    private FileStorageService fileStorageService;//注入实列

    @Autowired
    TokenService tokenService;

    @Autowired
    private SftpProperties sftpProperties;




    /**
     * 将文件存储到oss和本地
     */
    @Anonymous
    @PutMapping("/filePath/{id}")
    public AjaxResult uploadFile(@PathVariable Long id,@RequestParam MultipartFile file) throws Exception {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件为空");
            }

            // 获取 base-path
            String basePath = "administrationFilePath/"; // 直接在这里设置基础路径，或者从配置文件中读取

            // 指定oss保存文件路径
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + file.getOriginalFilename();
            // 上传图片，成功返回文件信息
            FileInfo fileInfo = fileStorageService.of(file).setPath(objectName).upload();

            // 设置返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileInfo.getUrl());
            ajax.put("fileName", fileInfo.getUrl());  // 注意：这里的值要改为url，前端访问的地址,需要文件的地址 而不是文件名称
            ajax.put("newFileName", fileInfo.getUrl());
            ajax.put("originalFilename", file.getOriginalFilename());

            // 创建Administration对象并设置ID和filePath
            Administration administration = new Administration();
            administration.setId(id); // 你需要实现一个方法来生成唯一的ID，或者从其他地方获取ID
            administration.setFilePath(fileInfo.getUrl());

            // 更新数据库中的filePath字段
            boolean result = administrationService.updateById(administration);
            if (!result) {
                return AjaxResult.error("更新文件路径失败");
            }

            return ajax;

        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 更新审批管理文件路径,保存在远程服务器
     */
    @Anonymous
    @PutMapping("/updateRemoteFilepath/{id}")
    public AjaxResult remote(@PathVariable Long id, @RequestParam MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return AjaxResult.error("上传文件为空");
        }

        try {
            // 使用配置文件中的参数上传到远程服务器
            String fileUrl = FileUploadUtil.uploadFileToRemoteServer(
                    sftpProperties.toSftpConfig(),
                    file,
                    "administrationFilePath"
            );

            // 设置返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileUrl);

            Administration administration = new Administration();
            administration.setId(id);
            administration.setFilePath(fileUrl);

            boolean result = administrationService.updateById(administration);
            if (!result) {
                return AjaxResult.error("更新失败");
            }
            return ajax;

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("文件上传失败: " + e.getMessage());
        }
    }



    /**
     * 更新审批管理文件路径,保存在本地
     */

    @Anonymous
    @PutMapping("/updateFilepath/{id}")
    public AjaxResult updateFilepath(@PathVariable Long id, @RequestParam MultipartFile file) {

        // 检查文件是否为空
        if (file.isEmpty()) {
            return AjaxResult.error("上传文件为空");
        }
        // 获取 base-path
        String basePath = "administrationFilePath/"; // 直接在这里设置基础路径，或者从配置文件中读取

        // 指定oss保存文件路径
        String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + file.getOriginalFilename();
        // 上传图片，成功返回文件信息
        FileInfo fileInfo = fileStorageService.of(file).setPath(objectName).upload();

        // 设置返回结果
        AjaxResult ajax = AjaxResult.success();
        ajax.put("url", fileInfo.getUrl());
        ajax.put("fileName", fileInfo.getUrl());  // 注意：这里的值要改为url，前端访问的地址,需要文件的地址 而不是文件名称
        ajax.put("newFileName", fileInfo.getUrl());
        ajax.put("originalFilename", file.getOriginalFilename());
        Administration administration = new Administration();
        administration.setId(id);
        administration.setFilePath(fileInfo.getUrl());

        boolean result = administrationService.updateById(administration);
        if (!result) {
            return AjaxResult.error("更新失败");
        }
        return ajax;
    }

    /**
     * 查询审批种类
     */
    @GetMapping("/kind")
    public TableDataInfo selectKindList() {
        // 1. 启用分页（自动读取前端的 pageNum 和 pageSize）
        startPage();

        // 2. 查询数据列表（PageHelper 会自动拦截并分页）
        List<Kind> kindList = administrationService.selectKindList();

        // 3. 转换为前端需要的格式
        List<Map<String, Object>> kindOptions = new ArrayList<>();
        for (Kind kind : kindList) {
            Map<String, Object> option = new HashMap<>();
            option.put("kind", kind.getKind());
            option.put("id", kind.getId());
            kindOptions.add(option);
        }

        // 4. 返回分页数据（TableDataInfo 是若依封装的分页响应类）
        return getDataTable(kindOptions);
    }

    /**
     * 查询审批管理列表 单权限版
     */
//    @PreAuthorize("@ss.hasPermi('administration:administration:list')")
    @PreAuthorize("@ss.hasPermi('administration:administration:list')")
    @GetMapping("/list")
    public Map<String,Object> list(Administration administration)
    {
        LoginUser loginUser=tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser=loginUser.getUser();
        // 获取当前用户的 user_name
        //String user_name = sysUser.getUserName();
        List<String> allowedRoles = Arrays.asList("administrationManager","admin");

        boolean hasAdministrationAllPermission = sysUser.getRoles().stream()
                .anyMatch(role -> allowedRoles.contains(role.getRoleKey()));


        startPage();
        List<Administration> list = administrationService.selectAdministrationList(administration);
        TableDataInfo tableDataInfo = getDataTable(list);
        HashMap<String, Object> result = new HashMap<>();
        result.put("data",tableDataInfo);
        result.put("canAudit", hasAdministrationAllPermission);
        //返回roleKey
//        result.put("role", sysUser.getRoles());
//        result.put("userName",user_name);
        System.out.println("result="+result);

        return result;
    }

    /**
     * 导出审批管理列表
     */
//    @PreAuthorize("@ss.hasPermi('administration:administration:export')")
    @Anonymous
    @Log(title = "审批管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Administration administration)
    {
        List<Administration> list = administrationService.selectAdministrationList(administration);
        ExcelUtil<Administration> util = new ExcelUtil<Administration>(Administration.class);
        util.exportExcel(response, list, "审批管理数据");
    }

    /**
     * 获取审批管理详细信息
     *
     */
//    @PreAuthorize("@ss.hasPermi('administration:administration:query')")
    @Anonymous
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(administrationService.selectAdministrationById(id));
    }


    /**
     * 根据Kind获取审批管理详细信息
     */
//    @PreAuthorize("@ss.hasPermi('administration:administration:query')")
    @GetMapping(value = "/kindkind")
    public TableDataInfo getInfoByKind(@RequestParam(required = false) String kind) {
        // 1. 启用分页（自动读取前端的 pageNum 和 pageSize）
        startPage();

        // 2. 查询数据列表（PageHelper 会自动拦截并分页）
        List<Administration> list = administrationService.selectAdministrationByKind(kind);

        // 3. 返回分页数据（TableDataInfo 是若依封装的分页响应类）
        return getDataTable(list);
    }

    /**
     * 新增审批管理
     */
    @Anonymous
//    @PreAuthorize("@ss.hasPermi('administration:administration:add')")
    @Log(title = "审批管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Administration administration)
    {
        return toAjax(administrationService.insertAdministration(administration));
    }

    /**
     * 新增审批管理以及文件上传
     */
    @Anonymous
//    @PreAuthorize("@ss.hasPermi('administration:administration:add')")
    @Log(title = "审批管理", businessType = BusinessType.INSERT)
    @PostMapping("/addAdministration")
    public AjaxResult addAdministration(
            @RequestParam Map<String, String> administration,
            @RequestParam(value = "filePath",required = false) MultipartFile file)
    {
        Administration administration1 = new Administration();
        if (administration.get("item") != null)
            administration1.setItem(administration.get("item"));
        if (administration.get("number") != null)
            administration1.setNumber(administration.get("number"));
        if (administration.get("film") != null)
            administration1.setFilm(administration.get("film"));
        if (administration.get("state") != null)
            administration1.setState(administration.get("state"));
        if (administration.get("kind") != null)
            administration1.setKind(administration.get("kind"));
        if (administration.get("writer") != null)
            administration1.setWriter(administration.get("writer"));
        if (administration.get("pubdate") != null)
            administration1.setPubdate(administration.get("pubdate"));
        if (administration.get("origin") != null)
            administration1.setOrigin(administration.get("origin"));
        if (administration.get("click") != null)
            administration1.setClick(Long.valueOf(administration.get("click")));
        if (administration.get("date") != null)
            administration1.setDate(administration.get("date"));

        try {
            if (file != null && !file.isEmpty()){
                // 获取 base-path
                String basePath = "administrationFilePath/"; // 直接在这里设置基础路径，或者从配置文件中读取

                // 指定oss保存文件路径
                String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + file.getOriginalFilename();
                // 上传图片，成功返回文件信息
                FileInfo fileInfo = fileStorageService.of(file).setPath(objectName).upload();

                // 设置返回结果
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", fileInfo.getUrl());
                ajax.put("fileName", fileInfo.getUrl());  // 注意：这里的值要改为url，前端访问的地址,需要文件的地址 而不是文件名称
                ajax.put("newFileName", fileInfo.getUrl());
                ajax.put("originalFilename", file.getOriginalFilename());

                //filePath
                administration1.setFilePath(fileInfo.getUrl());
            }
            else
                administration1.setFilePath(null);


        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return toAjax(administrationService.insertAdministration(administration1));
    }

    /**
     * 修改审批管理
     */
    @Anonymous
//    @PreAuthorize("@ss.hasPermi('administration:administration:edit')")
    @Log(title = "审批管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Administration administration)
    {
        return toAjax(administrationService.updateAdministration(administration));
    }

    /**
     * 删除审批管理
     */
    @Anonymous
//    @PreAuthorize("@ss.hasPermi('administration:administration:remove')")
    @Log(title = "审批管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(administrationService.deleteAdministrationByIds(ids));
    }

    /**
     * 逻辑删除审批管理
     */
    @Anonymous
    @Log(title = "审批管理", businessType = BusinessType.DELETE)
    @PostMapping("/deleteLogic/{ids}")
    public TableDataInfo deleteLogic(@PathVariable Long[] ids)
    {
        List<AdsRecoverStation> adsRecoverStations = new ArrayList<>();
        adsRecoverStations = administrationService.updateAdsDeletedStatus(ids);
        return getDataTable(adsRecoverStations);
    }
}
